<?php

include_once FCPATH . 'application/controllers/frontend.php';

class Home extends Frontend {

	public function __construct() {
		parent::__construct();
	}

	public function index() {
		$this->rend('home_index_view');
	}

	public function records() {
		$page = intval($this->input->get('page'));
		$page_size = intval($this->input->get('pageSize'));
		$page = $page ? $page : 1;
		$page_size = $page_size ? $page_size : 10;
		$offset = $page_size * ($page - 1);

		$lang = $this->input->cookie('lang') == 'en' ? '_en' : '';

		$entry_total_sql = "SELECT COUNT(`id`) as `total` FROM `jd_entry` WHERE `type` > 0 and `display`=1;";
		$project_totle_sql = "SELECT COUNT(`id`) as `total` FROM `jd_project` where `display`=1;";
		$entry_total_query = $this->db->query($entry_total_sql);
		$project_total_query = $this->db->query($project_totle_sql);
		$total = max($entry_total_query->row()->total,$project_total_query->row()->total);

		$records_sql = "select * from
	(
		SELECT
			e.id as id,
			e.album as album,
			e.type as type,
			e.title{$lang} as title,
			e.content{$lang} as content,
			e.created_at as created_at,
			p.file_name as cover_name,
			1 as kindof
		FROM
			`jd_entry` e
		LEFT JOIN
			`jd_album` a
		ON e.album=a.id
		LEFT JOIN `jd_photo` p
		ON a.cover=p.id
		where e.`type` > 0 and e.`display`=1
		ORDER BY e.`created_at` desc
		limit {$offset},{$page_size}
	) e
	union
	(
		select
			p.id as id,
			p.album as album,
			0 as type,
			p.title{$lang} as title,
			p.content{$lang} as content,
			p.created_at as created_at,
			ph.file_name as cover_name,
			2 as kindof
		from `jd_project` p
		left join `jd_album` a
		on p.album=a.id
		left join `jd_photo` ph
		on a.cover=ph.id
		where p.`display`=1
		ORDER BY p.`order` desc
		limit {$offset},{$page_size}
	);";

		$query = $this->db->query($records_sql);

		$this->json_back('XT001', '', array(
			'total' => $total,
			'records' => $query->result()
		));
	}

}
